<?php
/**
 *
 * Controller for the cart
 *
 * @package	mvm
 * @subpackage paypal
 * @author Zbigniew Mazur
 * @link http://promobico.com
 * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
 * VirtueMart is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

// Load the controller framework
jimport('joomla.application.component.controller');


//there is no class inside
if(!class_exists('PayPalhelper')) require(JPATH_COMPONENT.DS.'helpers'.DS.'paypalfunctions.php');


//for the cart data
if(!class_exists('VirtueMartCart')) require(JPATH_COMPONENT.DS.'helpers'.DS.'cart.php');

define (CANCEL_URL, JURI::root() . urlencode ( "?option=com_mvm&view=paypal&task=paypal.CanceledTrnasaction&format=json" . "&XDEBUG_SESSION_START=ECLIPSE_DBGP"));


/**
 * Controller for the cart view
 *
 * @package MVM
 * @subpackage Paypal
 * @author Zbigniew Mazur
 */
class MvmControllerPaypal extends JController {


	public function SetExpressCheckout() {
		$session = JFactory::getSession();
		// get cart info
		$cart = VirtueMartCart::getCart();
		$cart->prepareCartData();
		
		$paymentAmount = $cart->cartData->prices['billTotal'];
		$subtotal = $cart->cartData->prices['discountedPriceWithoutTax'];
		$taxamount = $cart->cartData->prices['taxAmount'];
		$shipping = $cart->cartData->prices['shippingValue'];
		
		$currencyCodeType = $cart->cartData->prices['currency'];
		//paymentType has to be one of the following values: Sale or Order or Authorization
		$paymentType = "SALE";
		$returnURL=urlencode ('http://rtd5rtd.com/jshop/?option=com_mvm&view=paypal&task=paypal.return&format=json&XDEBUG_SESSION_START=ECLIPSE_DBGP');
//		$cancelURL=urlencode ('http://rtd5rtd.com/jshop/?option=com_mvm&view=paypal&task=paypal.return&format=json&XDEBUG_SESSION_START=ECLIPSE_DBGP');
		$returnURL=urlencode (JURI::root() . "?option=com_mvm&view=paypal&task=paypal.getDetails&format=json" . "&XDEBUG_SESSION_START=ECLIPSE_DBGP");
//		$cancelURL=urlencode (JURI::root() . "?option=com_mvm&view=paypal&task=paypal.CanceledTrnasaction&format=json" . "&XDEBUG_SESSION_START=ECLIPSE_DBGP");
		$cancelURL=CANCEL_URL;
		
		//	$returnURL=JRequest::getVar('returnUrl');
		//$cancelURL=JRequest::getVar('cancelUrl');
		$appid = JRequest::getVar('appId');

		/*Allowable values: 0, 1, 2
		 * 0 - PayPal displays the shipping address on the PayPal pages
		 * 1 - PayPal does not display shipping address fields whatsoever
		 * 2 - If you do not pass the shipping address, PayPal obtains it from the buyer’s account profile
		 */
		$noshipping = 0; // shipping = BT for now
		$email = $session->get('email', null, 'vm');

		// get token from the device
		$drt = JRequest::getVar('deviceToken');

		// call paypal function SetExpressCheckout
		// recieve the checkout token from paypal
		$resArray = PaypalHelper::getInstance()->CallShortcutExpressCheckout ($paymentAmount, $subtotal, $taxamount, $shipping,
						$currencyCodeType, 
						$paymentType, 
						$returnURL, 
						$cancelURL, 
						$noshipping=1, 
						$email);
						
		$ack = strtoupper($resArray['ACK']);
		
		if($ack=="SUCCESS" || $ack=="SUCCESSWITHWARNING")
		{
			$session->set('deviceToken', $drt, 'vm');
			$session->set('checkoutToken', $resArray["TOKEN"], "vm");		
			$session->set('paymentType', $paymentType, 'vm');
			$session->set('payerId', $resArray["PAYERID"], 'vm');
			PaypalHelper::getInstance()->RedirectToPayPal ( $resArray["TOKEN"], 
																$resArray['TIMESTAMP'], 
																$resArray['CORRELATIONID'], 
																$resArray["VERSION"],
																$drt);
		}
		else
		{
			//Display a user friendly Error on the page using any of the following error information returned by PayPal
			$ErrorCode = urldecode($resArray["L_ERRORCODE0"]);
			$ErrorShortMsg = urldecode($resArray["L_SHORTMESSAGE0"]);
			$ErrorLongMsg = urldecode($resArray["L_LONGMESSAGE0"]);
			$ErrorSeverityCode = urldecode($resArray["L_SEVERITYCODE0"]);
			
			$error_message = "SetExpressCheckout API call failed. ";
			$error_message +="Detailed Error Message: " . $ErrorLongMsg;
			$error_message +="Short Error Message: " . $ErrorShortMsg;
			$error_message +="Error Code: " . $ErrorCode;
			$error_message +="Error Severity Code: " . $ErrorSeverityCode;
			header("Location: ", CANCEL_URL);
		}
		
	}
	
	public function getDetails() {
		$session = JFactory::getSession();
		$checkoutToken = $session->get('checkoutToken', null, 'vm');

		$resArray = PaypalHelper::getInstance()->GetShippingDetails($checkoutToken);
		
		$session->set('payerId', $resArray['PAYERID'], 'vm');
		$ack = strtoupper($resArray['ACK']);
		if($ack == "SUCCESS" || $ack=="SUCCESSWITHWARNING") {
			echo $this->doPayment();
		} else {
			$error_message;	
			header("Location: ", CANCEL_URL);
		}
	}
	
	private function doPayment() {
		// get cart and session
		$cart = VirtueMartCart::getCart();
		$cart->prepareCartData();
		
		return $cart->confirmOrder();
	}
		
}
